#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<sys/time.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>


int count1 = 1, count2 = 2;
pthread_mutex_t lock1, lock2;

void printferor(char* const str,int ret){
    fprintf(stderr, "%s error: %s\n", str, strerror(ret));
    exit(1);
}

void* myfunc1 (void*){
   pthread_mutex_lock(&lock1);
   sleep(2);
   pthread_mutex_lock(&lock2);
   printf("count 1 is %d\n", count1);
   pthread_mutex_unlock(&lock1);
   pthread_mutex_unlock(&lock2); 
}

void* myfunc2 (void*){
   pthread_mutex_lock(&lock2);
   sleep(1);
   pthread_mutex_lock(&lock1);
   printf("count 2 is %d\n", count2);
   pthread_mutex_unlock(&lock2);
   pthread_mutex_unlock(&lock1); 
}

int main(int argc, char* args[])
{   
    int ret = 0;
    //两把钥匙上锁
    ret = pthread_mutex_init(&lock1, NULL);
    if(ret)
        printferor("pthread_mutex_init", ret);
    ret = pthread_mutex_init(&lock2, NULL);
    if(ret)
        printferor("pthread_mutex_init", ret);

    //创建两线程
    pthread_t tid1, tid2;
    ret = pthread_create(&tid1, NULL, myfunc1, NULL);
    if(ret)
        printferor("pthread_create", ret);
    pthread_create(&tid2, NULL, myfunc2, NULL);
    if(ret)
        printferor("pthread_create", ret);
    
    // 回收两线程
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    //销毁两把锁
    pthread_mutex_destroy(&lock1);
    pthread_mutex_destroy(&lock2);

    return 0;
     

}